package com.itheima.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.pojo.OrderDetail;
import com.itheima.pojo.Orders;
import com.itheima.dto.OrdersDto;
import com.itheima.service.OrderDetailService;
import com.itheima.service.OrdersService;
import com.itheima.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/order")
public class OrdersController {
    @Autowired
    public OrdersService ordersService;

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private OrderDetailService orderDetailService;


    //支付，生成订单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
//        Long userId = BaseContext.getCurrentId();
//        // 1、查询购物车数据：select * from shopping_cart where user_id = ?
//        LambdaQueryWrapper<ShoppingCart> lqw = new LambdaQueryWrapper<>();
//        lqw.eq(userId != null,ShoppingCart::getUserId,userId);
//        List<ShoppingCart> shoppingCarts = shoppingCartService.list(lqw);
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    //分页查询订单
    @GetMapping("/userPage")
    public R<Page> userPage(Integer page,Integer pageSize){
        //Orders orders = new Orders();
        Page<Orders> pageOrders = new Page<>(page,pageSize);
        Page<OrdersDto> dtoPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getUserId);
        ordersService.page(pageOrders, lqw);
        BeanUtils.copyProperties(pageOrders,dtoPage,"records");
        List<OrdersDto> list = new ArrayList<>();
        List<Orders> records = pageOrders.getRecords();
        //List<Orders> orderslist = ordersService.list();
        //List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,record.getNumber());
            List<OrderDetail> list1 = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(list1);
            list.add(ordersDto);
        }
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    //后台分页查询订单
    @GetMapping("/page")
    public R<Page> orderPage(Integer page,Integer pageSize){
        Page<Orders> pageOrders = new Page<>(page,pageSize);
        Page<OrdersDto> dtoPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Orders::getUserId);
        ordersService.page(pageOrders, lqw);
        BeanUtils.copyProperties(pageOrders,dtoPage,"records");
        List<OrdersDto> list = new ArrayList<>();
        List<Orders> records = pageOrders.getRecords();
        //List<Orders> orderslist = ordersService.list();
        //List<OrdersDto> ordersDtos = new ArrayList<>();
        for (Orders record : records) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(record,ordersDto);
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,record.getNumber());
            List<OrderDetail> list1 = orderDetailService.list(lambdaQueryWrapper);
            ordersDto.setOrderDetails(list1);
            list.add(ordersDto);
        }
        dtoPage.setRecords(list);
        return R.success(dtoPage);
    }

    //excel导出订单数据
    @GetMapping("/export")
    public void exportExcel(String beginTime, String endTime, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = UUID.randomUUID().toString();
        response.setHeader("Content-disposition","attachment;filename*=utf-8''"+fileName+".xlsx");
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //select * from where reate_time between ? and ?
        lqw.between(StringUtils.isNotEmpty(beginTime)&&StringUtils.isNotEmpty(endTime),//动态SQL
                Orders::getOrderTime,
                beginTime,
                endTime);
        List<Orders> list = ordersService.list(lqw);
        EasyExcel.write(response.getOutputStream(),Orders.class).sheet("模板").doWrite(list);
    }
}
